package WEB.Servlet;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

public class WebServlet extends javax.servlet.http.HttpServlet {
    private static final Logger log = Logger.getLogger(WebServlet.class.getName());

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        BasicConfigurator.configure();
        log.info("init() complete");
    }

    @Override
    public void destroy() {
        super.destroy();
        log.info("destroy() complete");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        final HttpSession session = req.getSession(true);
        final Integer reqcount = (Integer) session.getAttribute("req_count");
        if (reqcount == null) {
            session.setAttribute("req_count", 1);
        } else {
            session.setAttribute("req_count", reqcount + 1);
        }

        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");

        
        final PrintWriter w = resp.getWriter();
        w.write("<html><body>");

        final Map params = req.getParameterMap();
        for (Iterator paramNameIt = params.keySet().iterator(); paramNameIt.hasNext();) {
            String paramName = (String) paramNameIt.next();
            w.write(paramName + "=>" + Arrays.toString(req.getParameterValues(paramName))+"<br/>");
        }
        w.write("</body></html>");
    }
     @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        final PrintWriter w = resp.getWriter();
        w.write("<html><body>");
        w.write("request URL: " + req.getRequestURL() + "<br/>");
        w.write("request URI: " + req.getRequestURI() + "<br/>");
        w.write("request QS: " + req.getQueryString() + "<br/>");
        w.write("request CP: " + req.getContextPath() + "<br/>");
        final Map params = req.getParameterMap();
        w.write("param count: " + params.keySet().size() + "<br/>");
        for (Iterator paramNameIt = params.keySet().iterator(); paramNameIt.hasNext();) {
            String paramName = (String) paramNameIt.next();
            w.write(paramName + "=>" + Arrays.toString(req.getParameterValues(paramName))+"<br/>");
        }
        w.write("</body></html>");
    }
}
